// 视频流管理
class VideoFeed {
    constructor() {
        this.videoGrid = document.querySelector('.video-grid');
        this.loadingSpinner = document.querySelector('.loading-spinner');
        this.videoItems = [];
        this.currentIndex = 0;
        this.isLoading = false;
        this.hasMore = true;
        this.page = 1;
        this.pageSize = 10;
        this.currentVideo = null;

        // 初始化
        this.init();
    }

    init() {
        console.log('初始化视频流...');
        this.loadVideos();
    }

    async loadVideos() {
        try {
            console.log('加载视频列表...');
            this.showLoading();
            const response = await fetch('/api/videos');
            const data = await response.json();
            console.log('获取到视频数据:', data);
            
            if (data.videos && data.videos.length > 0) {
                this.renderVideos(data.videos);
            } else {
                this.showError('暂无视频内容');
            }
        } catch (error) {
            console.error('加载视频失败:', error);
            this.showError('加载视频失败，请稍后重试');
        } finally {
            this.hideLoading();
        }
    }

    renderVideos(videos) {
        console.log('渲染视频卡片...');
        this.videoGrid.innerHTML = videos.map(video => `
            <div class="video-card" data-video-id="${video.id}">
                <div class="video-thumbnail">
                    <video 
                        src="${video.url}" 
                        loop 
                        playsinline
                        preload="auto"
                        class="video-player"
                    ></video>
                    <div class="custom-progress-bar">
                        <div class="progress-track"></div>
                        <div class="progress-fill"></div>
                        <div class="progress-handle"></div>
                    </div>
                </div>
                <div class="video-info">
                    <h3 class="video-title">${video.title}</h3>
                    <p class="video-description">${video.description || ''}</p>
                </div>
                <div class="video-card-stats">
                    <img class="author-avatar" src="${video.author?.avatar || '/images/default-avatar.png'}" alt="作者头像">
                    <div class="stat-item">
                        <i class="fas fa-eye"></i>
                        <span>${video.views || 0}</span>
                    </div>
                    <div class="stat-item">
                        <i class="fas fa-heart"></i>
                        <span>${video.likes || 0}</span>
                    </div>
                    <div class="stat-item">
                        <i class="fas fa-comment"></i>
                        <span>${video.comments || 0}</span>
                    </div>
                    <div class="stat-item">
                        <i class="fas fa-star"></i>
                        <span>${video.favorites || 0}</span>
                    </div>
                    <div class="stat-item">
                        <i class="fas fa-share"></i>
                        <span>${video.shares || 0}</span>
                    </div>
                </div>
            </div>
        `).join('');

        this.setupVideoPlayback();
    }

    setupVideoPlayback() {
        const videoCards = this.videoGrid.querySelectorAll('.video-card');
        const videos = this.videoGrid.querySelectorAll('.video-player');
        
        // 创建 Intersection Observer 来检测视频是否在视口中
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                const video = entry.target;
                const videoCard = video.closest('.video-card');
                const progressBar = videoCard.querySelector('.custom-progress-bar');
                const progressFill = videoCard.querySelector('.progress-fill');
                const progressHandle = videoCard.querySelector('.progress-handle');
                
                if (entry.isIntersecting) {
                    // 视频进入视口，自动播放（有声音）
                    this.currentVideo = video;
                    video.muted = false;
                    
                    // 确保视频元数据已加载
                    if (video.readyState >= 1) {
                        // 元数据已加载，可以播放
                        console.log('元数据已加载，开始播放');
                        video.play().catch(e => {
                            console.warn('自动播放失败，需要用户交互:', e);
                        });
                    } else {
                        // 等待元数据加载
                        console.log('等待视频元数据加载');
                        video.addEventListener('loadedmetadata', () => {
                            console.log('元数据已加载，开始播放');
                            video.play().catch(e => {
                                console.warn('自动播放失败，需要用户交互:', e);
                            });
                        }, { once: true });
                    }
                    
                    // 添加视频点击事件（播放/暂停）
                    if (!video.hasClickListener) {
                        video.hasClickListener = true;
                        video.addEventListener('click', (e) => {
                            e.stopPropagation();
                            if (video.paused) {
                                video.play();
                            } else {
                                video.pause();
                            }
                        });
                    }
                    
                    // 更新进度条
                    if (!video.hasProgressListener) {
                        video.hasProgressListener = true;
                        
                        // 当视频播放时更新进度条
                        video.addEventListener('timeupdate', () => {
                            const progress = (video.currentTime / video.duration) * 100;
                            progressFill.style.width = `${progress}%`;
                            progressHandle.style.left = `${progress}%`;
                        });
                        
                        // 进度条点击和拖拽
                        progressBar.addEventListener('mousedown', function(e) {
                            e.stopPropagation();
                            e.preventDefault();
                            
                            // 检查视频元数据是否已加载
                            if (!video.duration || video.duration === Infinity || video.duration <= 0 || !video.dataset.metadataLoaded) {
                                console.warn('视频元数据尚未加载完成，无法调整进度');
                                return;
                            }
                            
                            // 保存初始位置和视频状态
                            const wasPlaying = !video.paused;
                            if (wasPlaying) video.pause();
                            
                            // 创建时长显示元素
                            let timeTooltip = videoCard.querySelector('.time-tooltip');
                            if (!timeTooltip) {
                                timeTooltip = document.createElement('div');
                                timeTooltip.className = 'time-tooltip';
                                videoCard.querySelector('.video-thumbnail').appendChild(timeTooltip);
                            }
                            
                            // 格式化时间函数
                            const formatTime = (seconds) => {
                                if (!seconds || !isFinite(seconds) || seconds < 0) {
                                    return '0:00';
                                }
                                
                                const totalSecs = Math.floor(seconds);
                                const minutes = Math.floor(totalSecs / 60);
                                const secs = totalSecs % 60;
                                
                                // 处理小时（如果超过60分钟）
                                if (minutes >= 60) {
                                    const hours = Math.floor(minutes / 60);
                                    const mins = minutes % 60;
                                    return `${hours}:${mins < 10 ? '0' + mins : mins}:${secs < 10 ? '0' + secs : secs}`;
                                }
                                
                                return `${minutes}:${secs < 10 ? '0' + secs : secs}`;
                            };
                            
                            // 创建防抖函数
                            const debounce = (func, delay) => {
                                let timeout;
                                return (...args) => {
                                    clearTimeout(timeout);
                                    timeout = setTimeout(() => func(...args), delay);
                                };
                            };
                            
                            // 直接处理点击位置
                            const handleProgressClick = function(x) {
                                // 检查视频时长是否有效
                                if (!video.duration || !isFinite(video.duration) || video.duration <= 0) {
                                    console.error('视频时长无效:', video.duration);
                                    return 0;
                                }
                                
                                console.log('当前视频时长:', video.duration, '秒');
                                
                                // 每次获取最新的进度条尺寸
                                const rect = progressBar.getBoundingClientRect();
                                console.log('进度条宽度:', rect.width, '位置:', x - rect.left);
                                
                                // 计算点击位置相对于进度条的比例（0-1之间）
                                let ratio = (x - rect.left) / rect.width;
                                // 限制在有效范围内
                                ratio = Math.max(0, Math.min(1, ratio));
                                console.log('计算比例:', ratio);
                                
                                // 计算视频时间
                                const newTime = video.duration * ratio;
                                console.log('设置视频时间:', newTime, '秒');
                                
                                // 设置视频播放时间
                                video.currentTime = newTime;
                                
                                // 立即更新UI，不等待timeupdate事件
                                progressFill.style.width = `${ratio * 100}%`;
                                progressHandle.style.left = `${ratio * 100}%`;
                                
                                // 显示时间提示
                                timeTooltip.textContent = formatTime(newTime);
                                // 计算提示位置并显示
                                const tooltipPos = Math.min(rect.width - timeTooltip.offsetWidth, Math.max(0, x - rect.left));
                                timeTooltip.style.left = `${tooltipPos}px`;
                                timeTooltip.style.display = 'block';
                                
                                return ratio;
                            };
                            
                            // 防抖版处理拖动
                            const debouncedHandleDrag = debounce((e) => {
                                handleProgressClick(e.clientX);
                            }, 10); // 10ms防抖延迟
                            
                            // 处理当前点击
                            handleProgressClick(e.clientX);
                            
                            // 拖动处理函数
                            const handleDrag = function(e) {
                                e.preventDefault();
                                
                                // 立即更新UI显示
                                const rect = progressBar.getBoundingClientRect();
                                const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
                                progressFill.style.width = `${ratio * 100}%`;
                                progressHandle.style.left = `${ratio * 100}%`;
                                
                                // 更新时间提示
                                const newTime = video.duration * ratio;
                                timeTooltip.textContent = formatTime(newTime);
                                const tooltipPos = Math.min(rect.width - timeTooltip.offsetWidth, Math.max(0, e.clientX - rect.left));
                                timeTooltip.style.left = `${tooltipPos}px`;
                                
                                // 防抖更新视频时间
                                debouncedHandleDrag(e);
                            };
                            
                            // 拖动结束处理函数
                            const stopDrag = function() {
                                document.removeEventListener('mousemove', handleDrag);
                                document.removeEventListener('mouseup', stopDrag);
                                // 隐藏时间提示
                                timeTooltip.style.display = 'none';
                                if (wasPlaying) video.play();
                            };
                            
                            // 添加拖动事件监听
                            document.addEventListener('mousemove', handleDrag);
                            document.addEventListener('mouseup', stopDrag);
                        });
                    }
                    
                    // 键盘控制
                    if (!videoCard.hasKeyboardControl) {
                        videoCard.hasKeyboardControl = true;
                        videoCard.tabIndex = 0; // 使元素可接收焦点
                        
                        videoCard.addEventListener('keydown', (e) => {
                            // 空格键：播放/暂停
                            if (e.code === 'Space') {
                                e.preventDefault();
                                if (video.paused) {
                                    video.play();
                                } else {
                                    video.pause();
                                }
                            }
                            // 左箭头：后退5秒
                            else if (e.code === 'ArrowLeft') {
                                e.preventDefault();
                                video.currentTime = Math.max(0, video.currentTime - 5);
                            }
                            // 右箭头：前进5秒
                            else if (e.code === 'ArrowRight') {
                                e.preventDefault();
                                video.currentTime = Math.min(video.duration, video.currentTime + 5);
                            }
                            // 上箭头：音量增加
                            else if (e.code === 'ArrowUp') {
                                e.preventDefault();
                                video.volume = Math.min(1, video.volume + 0.1);
                            }
                            // 下箭头：音量减小
                            else if (e.code === 'ArrowDown') {
                                e.preventDefault();
                                video.volume = Math.max(0, video.volume - 0.1);
                            }
                            // M键：静音切换
                            else if (e.code === 'KeyM') {
                                e.preventDefault();
                                video.muted = !video.muted;
                            }
                        });
                    }
                } else {
                    // 视频离开视口，暂停播放
                    video.pause();
                }
            });
        }, {
            threshold: 0.7 // 当视频显示70%时触发
        });

        // 观察所有视频元素
        videos.forEach(video => {
            observer.observe(video);
            
            // 添加视频加载事件
            video.addEventListener('loadeddata', () => {
                console.log('视频数据加载完成');
                // 预先加载第一帧
                video.currentTime = 0;
            });
            
            // 添加元数据加载事件
            video.addEventListener('loadedmetadata', () => {
                console.log('视频元数据加载完成，时长:', video.duration);
                // 标记视频元数据已加载
                video.dataset.metadataLoaded = 'true';
            });

            // 添加视频错误处理
            video.addEventListener('error', (e) => {
                console.error('视频加载错误:', e);
                // 显示错误占位图
                const thumbnail = document.createElement('img');
                thumbnail.src = '/images/default-thumbnail.jpg';
                thumbnail.alt = '视频无法加载';
                thumbnail.className = 'fallback-thumbnail';
                video.parentNode.replaceChild(thumbnail, video);
            });
        });

        // 添加滚动事件监听
        this.videoGrid.addEventListener('scroll', () => {
            // 可以在这里添加滚动相关的逻辑
        });
    }

    showLoading() {
        this.loadingSpinner.style.display = 'flex';
    }

    hideLoading() {
        this.loadingSpinner.style.display = 'none';
    }

    showError(message) {
        this.videoGrid.innerHTML = `
            <div class="error-message">
                <i class="fas fa-exclamation-circle"></i>
                <p>${message}</p>
            </div>
        `;
    }
}

// 初始化视频流
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM加载完成，初始化视频流...');
    new VideoFeed();
}); 